import GSTC, { GSTCResult } from 'gantt-schedule-timeline-calendar';
import { useGanttStore } from '@/store/modules/ganttStore';

export function useGanttEvents(gstc: GSTCResult, store: ReturnType<typeof useGanttStore>) {
  const setupEventHandlers = () => {
    if (!gstc?.api) {
      console.error('GSTC API is not initialized');
      return;
    }

    // 双击编辑文章
    gstc.api.on('item-double-click', ({ item }: any) => {
      store.setActivePost(item.rowId);
    });

    // 拖拽调整时间
    gstc.api.on('item-time-change', async ({ items }: any) => {
      const updates = items.map((item: any) => ({
        id: item.rowId,
        startDate: item.time.start,
        endDate: item.time.end
      }));

      await store.updatePostTimeline(updates);
      gstc.api.refresh();
    });

    // 右键菜单
    gstc.api.on('context-menu', ({ event, items }: any) => {
      if (items.length === 1) {
        showContextMenu(event, items[0]);
      }
    });

    // 缩放事件
    gstc.api.on('zoom', ({ level }: any) => {
      store.setZoomLevel(level);
    });
  };

  const showContextMenu = (event: MouseEvent, item: any) => {
    const menuItems = [
      {
        label: '编辑文章',
        icon: 'el-icon-edit',
        action: () => store.setActivePost(item.rowId)
      },
      {
        label: '添加依赖',
        icon: 'el-icon-connection',
        action: () => startDependencyCreation(item.rowId)
      },
      {
        label: '标记里程碑',
        icon: 'el-icon-flag',
        action: () => createMilestoneForPost(item.rowId)
      }
    ];

    // 使用Element Plus的Dropdown组件显示菜单
    // 实际实现可能需要自定义上下文菜单组件
  };

  const startDependencyCreation = (postId: string) => {
    store.startDependencyCreation(postId);
  };

  const createMilestoneForPost = (postId: string) => {
    store.saveMilestone({
      postId,
      name: '新里程碑',
      date: new Date().toISOString(),
      priority: 1,
      completed: false,
      createdAt: new Date().toISOString()
    });
  };

  return { setupEventHandlers };
}
